import {BaseComp} from '../basecomp';
import { COMPTYPE, CONSTKEY, getTemplate } from '../utils';

/**
 * 所有easyui的基类
 */
export abstract class BaseEasyuiComp extends BaseComp{
    public $dom:JQuery; 
    public props:any;
    protected koContext;
    constructor(name, props, componentConfig){
        super(COMPTYPE.easyui);
        this.props = props;
        this.name = name;
        this.$dom = $($(componentConfig.element)[0].firstChild);
        let context = ko.contextFor(componentConfig.element);
        $.data(componentConfig.element, context);
        this.koContext = context;
    }
    
    /**
     * 根据参数创建组件的配置对象（核心方法）
     * @param options 配置参数 
     */
    protected createOptionsCore(options){
        let opt = null;
        if(options){
            opt = Object.create({});
            Object.getOwnPropertyNames(options).forEach(optKey=>{
                let tmpOpt = options[optKey];
                if(this.props.indexOf(optKey) > 0 && ko.isObservable(tmpOpt) ){
                    opt[optKey] = ko.unwrap(tmpOpt);
                }
                else if(optKey.substring(0,2) == 'on' && $.isFunction(tmpOpt)){
                    //事件
                    opt[optKey] = tmpOpt.bind(this);
                }else{
                    opt[optKey] = tmpOpt;
                }
            });
        } 
        return opt;
    }
    /**
     * 根据参数创建组件的配置对象
     * @param options 配置参数 
     */
    protected createOptions(options){
        return this.createOptionsCore(options);
    }
    /**
     * 绘制组件
     * @param options 
     */
    public paint(options:any){
        debugger
        let opt = this.createOptions(options);
        this.$dom[this.name](opt);
    }
    /**
    * 重置组件到初始化状态
    * @param options 配置项
    */
    public resetComp(options:any){
        let $parent = this.$dom.closest(`${CONSTKEY.CompPrefix}${this.name}`);

        //@ts-ignore
        this.destroy && this.destroy();
        let $dom = $(getTemplate(this.name));
        $parent.append($dom);
        this.$dom = $dom; 
    }
    
}